package com.xbongbong.paas.model.impl;

import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.field.LinkInfoPojo;
import com.xbongbong.paas.model.LinkDataModel;
import com.xbongbong.paas.pojo.vo.LinkDataListVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.vo.FormDataVO;
import com.xbongbong.pro.formdata.pojo.vo.LinkQueryVO;
import org.elasticsearch.action.search.SearchRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 吴峰
 * @date 2022/04/13 14:30
 */
@Service("linkDataModel")
public class LinkDataModelImpl implements LinkDataModel {


    private static final Logger LOG = LoggerFactory.getLogger(LinkDataModelImpl.class);

    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;

    @Override
    public LinkDataListVO filterLinkData(String corpid, LinkInfoPojo linkInfoPojo, PageRequest pageRequest, SearchRequest searchRequest, LinkQueryVO linkQueryVO, Integer page, Integer pageSize) throws XbbException {
        LinkDataListVO linkDataVO = new LinkDataListVO();
        try {
            XbbAggregatedPage<PaasFormDataEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest,  searchRequest,PaasFormDataEntityExt.class);
            if (esEntities == null) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
            }
            List<PaasFormDataEntityExt> resultList = esEntities.getContent();
            List<FormDataVO> formDataList = new ArrayList<>();

            resultList.forEach((item)->{
                FormDataVO formDataVO = new FormDataVO();
                BeanUtil.copyProperties(item, formDataVO);
                formDataList.add(formDataVO);
            });

            linkDataVO.setPaasFormDataESList(formDataList);
            long num = esEntities.getTotalElements();
            PageHelper pageHelper = new PageHelper(page, pageSize);
            pageHelper.setRowsCount((int) num);
            linkDataVO.setPageHelper(pageHelper);
        }catch (Exception e) {
            LOG.error("com.xbongbong.paas.model.impl.LinkDataModelImpl.filterLinkData 关联查询出错",e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return linkDataVO;
    }
}
